﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Serialization;

public partial class admin_Invoice : System.Web.UI.Page
{
    string where = ""; string wheref = ""; string name = ""; string type = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Session["userid"] == null) { Response.Redirect("../Default.aspx"); }
            else
            {
                permiso();
                PClient.Visible = false;
            }

        }
        else {
            if (TabContainer1.ActiveTab.ID == "TabProcessor")
            {
                AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabProcessor"));
                if (tabpanel != null)
                {
                    CrystalDecisions.Web.CrystalReportViewer CRProcessor1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRProcessor"));
                    if (CRProcessor1 != null) { CRProcessor1.ReportSource = Session["rptProcessor"]; }
                }
            }

            if (TabContainer1.ActiveTab.ID == "TabDriver")
            {
                AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabDriver"));
                if (tabpanel != null)
                {
                    CrystalDecisions.Web.CrystalReportViewer CRDriver1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRDriver"));
                    if (CRDriver1 != null) { CRDriver1.ReportSource = Session["rptDriver"]; }
                }
            }

            if (TabContainer1.ActiveTab.ID == "TabQC")
            {
                AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabQC"));
                if (tabpanel != null)
                {
                    CrystalDecisions.Web.CrystalReportViewer CRQC1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRQC"));
                    if (CRQC1 != null) { CRQC1.ReportSource = Session["rptQC"]; }
                }
            }

            if (TabContainer1.ActiveTab.ID == "TabPhotos")
            {
                AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabPhotos"));
                if (tabpanel != null)
                {
                    CrystalDecisions.Web.CrystalReportViewer CRPhotos1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRPhotos"));
                    if (CRPhotos1 != null) { CRPhotos1.ReportSource = Session["rptPhotos"]; }
                }
            }

            if (TabContainer1.ActiveTab.ID == "TabClient")
            {
                AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabClient"));
                if (tabpanel != null)
                {
                    CrystalDecisions.Web.CrystalReportViewer CRClient1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRClient"));
                    if (CRClient1 != null) { CRClient1.ReportSource = Session["rptClient"]; }
                }
            }

            DataSet dsclient = (DataSet)Session["dsclient"];
            if (dsclient != null)
            {
                gv_client.DataSource = dsclient.Tables[0];
                gv_client.DataBind();
            }
        }

    }

    protected void Page_Init(object sender, EventArgs e)
    {
        DataSet dsclient= (DataSet)Session["dsclient"];
        if (dsclient != null)
        {
            gv_client.DataSource = dsclient.Tables[0];
            gv_client.DataBind();
        }
        restricted();
    }

    public void restricted()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 10);
            //permiso = long.Parse(user.getRestricted().ToString());
            permiso = permi.int64C2;
        }
        if ((permiso & 1) == 1) { Response.Redirect(Request.UrlReferrer.ToString()); }

        if ((permiso & 128) != 128) { /*P_viewcart.Visible = false;  */     }

        if ((permiso & 4) != 4)
        {
            AjaxControlToolkit.TabPanel tabProc = new AjaxControlToolkit.TabPanel();
            tabProc.ID = "TabProcessor";
            tabProc.HeaderText = "Processor";
            Table tabla1 = new Table();
            tabla1.ID = "TableProc";
            tabla1.Width = 1000; tabla1.CellPadding = 0; tabla1.CellSpacing = 0;
            tabla1.HorizontalAlign = HorizontalAlign.Center;
            TableRow row1 = new TableRow();
            row1.HorizontalAlign = HorizontalAlign.Center;
            TableCell cell1 = new TableCell();
            cell1.Controls.Add(pprocessor);
            CrystalDecisions.Web.CrystalReportViewer CRProcessor = new CrystalDecisions.Web.CrystalReportViewer();
            CRProcessor.ID = "CRProcessor";
            CRProcessor.AutoDataBind = true;
            CRProcessor.Attributes.Add("Style", "padding-top:50px;");
            cell1.Controls.Add(CRProcessor);
            cell1.Attributes.Add("Style", "padding-top:30px;");
            row1.Cells.Add(cell1);
            tabla1.Controls.Add(row1);
            tabProc.Controls.Add(tabla1);
            TabContainer1.Tabs.Add(tabProc);
        }
        else
        {
            pprocessor.Visible = false;
        }

        if ((permiso & 8) != 8)
        {
            AjaxControlToolkit.TabPanel tabDri = new AjaxControlToolkit.TabPanel();
            tabDri.ID = "TabDriver";
            tabDri.HeaderText = "Driver";
            Table tabla1 = new Table();
            tabla1.Width = 1000; tabla1.CellPadding = 0; tabla1.CellSpacing = 0;
            tabla1.HorizontalAlign = HorizontalAlign.Center;
            TableRow row1 = new TableRow();
            row1.HorizontalAlign = HorizontalAlign.Center;
            TableCell cell1 = new TableCell();
            cell1.Controls.Add(pdriver);
            CrystalDecisions.Web.CrystalReportViewer CRDriver = new CrystalDecisions.Web.CrystalReportViewer();
            CRDriver.ID = "CRDriver";
            CRDriver.AutoDataBind = true;
            CRDriver.Attributes.Add("Style", "padding-top:50px;");
            cell1.Controls.Add(CRDriver);
            cell1.Attributes.Add("Style", "padding-top:30px;");
            row1.Cells.Add(cell1);
            tabla1.Controls.Add(row1);
            tabDri.Controls.Add(tabla1);
            TabContainer1.Controls.Add(tabDri);
        }
        else
        {
            pdriver.Visible = false;
        }

        if ((permiso & 16) != 16)
        {
            AjaxControlToolkit.TabPanel tabQC = new AjaxControlToolkit.TabPanel();
            tabQC.ID = "TabQC";
            tabQC.HeaderText = "Quality Check";
            Table tabla1 = new Table();
            tabla1.Width = 1000; tabla1.CellPadding = 0; tabla1.CellSpacing = 0;
            tabla1.HorizontalAlign = HorizontalAlign.Center;
            TableRow row1 = new TableRow();
            row1.HorizontalAlign = HorizontalAlign.Center;
            TableCell cell1 = new TableCell();
            cell1.Controls.Add(pqc);
            CrystalDecisions.Web.CrystalReportViewer CRQC = new CrystalDecisions.Web.CrystalReportViewer();
            CRQC.ID = "CRQC";
            CRQC.AutoDataBind = true;
            CRQC.Attributes.Add("Style", "padding-top:50px;");
            cell1.Controls.Add(CRQC);
            cell1.Attributes.Add("Style", "padding-top:30px;");
            row1.Cells.Add(cell1);
            tabla1.Controls.Add(row1);
            tabQC.Controls.Add(tabla1);
            TabContainer1.Controls.Add(tabQC);
        }
        else
        {
            pqc.Visible = false;
        }

        if ((permiso & 32) != 32)
        {
            AjaxControlToolkit.TabPanel tabPho = new AjaxControlToolkit.TabPanel();
            tabPho.ID = "TabPhotos";
            tabPho.HeaderText = "Photos";
            Table tabla1 = new Table();
            tabla1.Width = 1000; tabla1.CellPadding = 0; tabla1.CellSpacing = 0;
            tabla1.HorizontalAlign = HorizontalAlign.Center;
            TableRow row1 = new TableRow();
            row1.HorizontalAlign = HorizontalAlign.Center;
            TableCell cell1 = new TableCell();
            cell1.Controls.Add(pphotos);
            CrystalDecisions.Web.CrystalReportViewer CRPhotos = new CrystalDecisions.Web.CrystalReportViewer();
            CRPhotos.ID = "CRPhotos";
            CRPhotos.AutoDataBind = true;
            CRPhotos.Attributes.Add("Style", "padding-top:50px;");
            cell1.Controls.Add(CRPhotos);
            cell1.Attributes.Add("Style", "padding-top:30px;");
            row1.Cells.Add(cell1);
            tabla1.Controls.Add(row1);
            tabPho.Controls.Add(tabla1);
            TabContainer1.Controls.Add(tabPho);
        }
        else
        {
            pphotos.Visible = false;
        }

        if ((permiso & 64) != 64)
        {
            AjaxControlToolkit.TabPanel tabClie = new AjaxControlToolkit.TabPanel();
            tabClie.ID = "TabClient";
            tabClie.HeaderText = "Client";
            Table tabla1 = new Table();
            tabla1.Width = 1000; tabla1.CellPadding = 0; tabla1.CellSpacing = 0;
            tabla1.Attributes.Add("Style", "padding-left: 0px; margin-left: 0px;");
            tabla1.HorizontalAlign = HorizontalAlign.Center;
            TableRow row1 = new TableRow();
            row1.HorizontalAlign = HorizontalAlign.Center;
            TableCell cell1 = new TableCell();
            cell1.Controls.Add(pnlclient);
            cell1.Controls.Add(PClient);
            CrystalDecisions.Web.CrystalReportViewer CRClient = new CrystalDecisions.Web.CrystalReportViewer();
            CRClient.ID = "CRClient";
            CRClient.AutoDataBind = true;
            CRClient.Attributes.Add("Style", "padding-top:50px;");
            cell1.Controls.Add(CRClient);
            cell1.Attributes.Add("Style", "padding-top: 30px;");
            row1.Cells.Add(cell1);
            tabla1.Controls.Add(row1);
            tabClie.Controls.Add(tabla1);
            TabContainer1.Controls.Add(tabClie);
        }
        else
        {
            PClient.Visible = false;
            pnlclient.Visible = false;
            pnlDelete.Visible = false;
        }

    }
    public void permiso()
    {
        long permiso = 0;
        rUser user = (rUser)(Session["userid"]);
        if (user != null)
        {
            //permiso = long.Parse(user.getPermisoUser().ToString());
            RE_GenericBean permi = Utility.getPermisobyRuser(user, 10);
            permiso = permi.int64C1;
           
        }
        if ((permiso & 2) != 2)
        {
            ListItem li;
            li = new ListItem();
            li.Text = "Select One";
            li.Value = "Select One";
            cb_processor.Items.Add(li);
            cb_driver.Items.Add(li);
            cb_qc.Items.Add(li);
            cb_photos.Items.Add(li);
            cb_client.Items.Add(li);
            li = new ListItem();
            li.Text = user.getAlias() + "-" + user.getNombre() + " " + user.getApellido();
            li.Value = user.getAlias();
            cb_processor.Items.Add(li);
            cb_driver.Items.Add(li);
            cb_qc.Items.Add(li);
            cb_client.Items.Add(li);
            li = new ListItem();
            li.Text = user.getAlias() + "-" + user.getNombre() + " " + user.getApellido();
            li.Value = user.getUsuarioId();
            cb_photos.Items.Add(li);
            name = user.getAlias();

            if ((permiso & 128) != 128)
            {
                //P_viewcart.Enabled = false;
            }
            pacc1.Visible = false;
            pacc2.Visible = false;
        }
        else
        {
            //si tieme permisos para buwscar todo
            ListItem li = new ListItem();
            li.Value = "All";
            li.Text = "All";
            cb_driver.Items.Add(li);
            cb_processor.Items.Add(li);
            cb_qc.Items.Add(li);
            cb_photos.Items.Add(li);
            Utility.fillAgent("", 1, 1, cb_driver);
            Utility.fillAgent("", 3, 2, cb_processor);
            Utility.fillAgent("", 7, 1, cb_qc);
            Utility.fillAgent("", 10, 1, cb_qc);
            Utility.fillAgent("", 2, 1, cb_photos);
            Utility.fillAgent("", 13, 1, cb_photos);
            Utility.fillclients(cb_client, "All");
            Utility.fillaccounts(cb_acclient, "All");
            Utility.fillcompanies(cb_company, "All");

            name = "";
        }
        if ((permiso & 4) != 4)
        {
            cb_processor.Enabled = false;
            //cb_processor.Visible = false;
            pproc1.Enabled = false;
            pproc2.Enabled = false;
            for (int i = 0; i < cb_searchby.Items.Count; i++)
            {
                if (cb_searchby.Items[i].Value.Equals("processor")) { cb_searchby.Items.RemoveAt(i); }
            }
            lnk_searchfee.Enabled = false;
            pprocessor.Enabled = false;
        }
        else
        {
            if ((permiso & 2) != 2) { cb_processor.Items.Clear(); pproc1.Visible = false; pproc2.Visible = false; }

            Session["nameinvoice"] = name;

        }
        if ((permiso & 8) != 8)
        {
            cb_driver.Enabled = false;
            //cb_driver.Visible = false;
            pdriver1.Enabled = false;
            pdriver2.Enabled = false;
            for (int i = 0; i < cb_searchby.Items.Count; i++)
            {
                if (cb_searchby.Items[i].Value.Equals("driver")) { cb_searchby.Items.RemoveAt(i); }
            }
            lnk_searchfee0.Enabled = false;
            pdriver.Enabled = false;
        }
        else
        {

            if ((permiso & 2) != 2) { cb_driver.Items.Clear(); cb_driver.Visible = false; pdriver1.Visible = false; pdriver2.Visible = false; }
            Session["nameinvoice"] = name;

        }
        if ((permiso & 16) != 16)
        {
            cb_qc.Enabled = false;
            //cb_qc.Visible = false;
            pqc1.Enabled = false;
            pqc2.Enabled = false;
            for (int i = 0; i < cb_searchby.Items.Count; i++)
            {
                if (cb_searchby.Items[i].Value.Equals("qc")) { cb_searchby.Items.RemoveAt(i); }
            }
            lnk_searchfee1.Enabled = false;
            pqc.Enabled = false;
        }
        else
        {

            Session["nameinvoice"] = name;
            if ((permiso & 2) != 2) { cb_qc.Items.Clear(); cb_qc.Visible = false; pqc1.Visible = false; pqc2.Visible = false; }


        }
        if ((permiso & 32) != 32)
        {
            cb_photos.Enabled = false;
            //cb_photos.Visible = false;
            Pphotos1.Enabled = false;
            Pphotos2.Enabled = false;

            for (int i = 0; i < cb_searchby.Items.Count; i++)
            {
                if (cb_searchby.Items[i].Value.Equals("photos")) { cb_searchby.Items.RemoveAt(i); }
            }
            lnk_searchfee2.Enabled = false;
            pphotos.Enabled = false;
        }
        else
        {
            name = user.getUsuarioId();
            Session["nameinvoice"] = name;
            if ((permiso & 2) != 2) { cb_photos.Items.Clear(); cb_photos.Visible = false; Pphotos1.Visible = false; Pphotos2.Visible = false; }

        }

        if ((permiso & 64) != 64)
        {
            cb_client.Enabled = false;
            //cb_client.Visible = false;
            Pclient1.Enabled = false;
            Pclient2.Enabled = false;
            for (int i = 0; i < cb_searchby.Items.Count; i++)
            {
                if (cb_searchby.Items[i].Value.Equals("client")) { cb_searchby.Items.RemoveAt(i); }
            }
            lnk_searchfee3.Enabled = false;
            pnlclient.Enabled = false;
        }
        else
        {
            name = user.getUsuarioId();
            Session["nameinvoice"] = name;
            if ((permiso & 2) != 2) { cb_client.Items.Clear(); cb_client.Visible = false; Pclient1.Visible = false; Pclient2.Visible = false; pcomp1.Visible = false; pcomp2.Visible = false; }

        }
            if (cb_searchby.Items.Count==2){
                Session["typeinvoice"] = cb_searchby.Items[1].Value;
                cb_searchby.Visible = false;
                cb_searchby.Enabled = false;
                ltype.Visible = false;
               /*  Pphotos1.Visible = false;
                Pphotos2.Visible = false;
                pqc1.Visible = false;
                pqc2.Visible = false;
                pdriver1.Visible = false;
                pdriver2.Visible = false;
                pproc1.Visible = false;
                pproc2.Visible = false;
                Pclient1.Visible = false;
                Pclient2.Visible = false;*/
            }else if (cb_searchby.Items.Count==1){
                lnk_searchfee.Visible = false;
                tb_stardatefee.Visible = false;
                tb_enddatefee.Visible = false;
                cb_searchby.Visible = false;
                cb_searchby.Enabled = false;
                lb_enddate.Visible = false;
                lb_startdate.Visible = false;
                ltype.Visible = false;
            }
    }

    private void PaypalButt(string usuid, string ammount, string name)
    {
        
        string butadd = "<form   action=\"https://www.paypal.com/cgi-bin/webscr\" method=\"post\"><input type=\"hidden\" name=\"cmd\" value=\"_cart\"/>";
        butadd += "<input type=\"hidden\" name=\"business\" value=\"UC5TPPY3Z8XBN\"/><input type=\"hidden\" name=\"display\" value=\"0\"/>  <input type=\"hidden\" name=\"add\" value=\"1\"/><input type=\"hidden\" name=\"lc\" value=\"US\"/>";
        butadd += "<input type=\"hidden\" name=\"amount\" value=\"" + ammount + "\" /><input type=\"hidden\" name=\"currency_code\" value=\"USD\"/> ";
        butadd += "<input type=\"hidden\" name=\"item_name\" value=\""+ usuid+"\"/>";
        butadd += "<input type=\"hidden\" name=\"item_number\" value=\"" + name +"\" />";
        butadd += "<input type=\"image\" src=\"https://www.paypal.com/en_US/i/btn/x-click-but10.gif\"  name=\"submit\" alt=\"PayPal - The safer, easier way to pay online!\"./></form>";


        lbuy.Text = butadd;

     

    }


    private void mostrarReporte()
    {
        string parametro = "";
        string currency = "";
        string fee = " fee ";
        int driver = 0, processor = 0, qc = 0, photos = 0, client = 0;
        string style = "General";
        if (cb_searchby.SelectedIndex != 0 && cb_searchby.SelectedIndex!= -1)
        {
            if (!cb_searchby.SelectedValue.ToUpper().Equals("PHOTOS") && !cb_searchby.SelectedValue.ToUpper().Equals("CLIENT"))
            {
               // where = " case when orden.ord_failed_" + cb_searchby.SelectedValue.ToString() + " is null then  orden.ord_" + cb_searchby.SelectedValue.ToString() + "_done else orden.ord_" + cb_searchby.SelectedValue.ToString() + "_done  end = 'YES'";
                where = " orden.ord_" + cb_searchby.SelectedValue.ToString() + "_done  = 'YES' ";
            }
            else {
                if (cb_searchby.SelectedValue.ToUpper().Equals("PHOTOS") ) { where = "   orden.ord_uploadby is not null "; }
                if (cb_searchby.SelectedValue.ToUpper().Equals("CLIENT")) { where = "   orden.status_id <> 0 "; }
            }
            
            parametro =  cb_searchby.SelectedValue.ToString();
            currency = "GTQ";
            style= "General";
            if (cb_searchby.SelectedValue.ToUpper().Equals("DRIVER"))
            {
                currency = "USD";
                driver = 1;
                if (uiChbFee.Checked) { fee = " CASE WHEN orden.driver_fee is null then 0.00 ELSE orden.driver_fee END"; }
                else { fee = "  CASE WHEN orden.company = 1  THEN orden.fee ELSE orden.psfprice END "; }
                if (!tb_stardatefee0.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee0.Text.Split('/');
                    //where = where + " and  case when orden.ord_failed_driver is null then orden.ord_driver_date else orden.ord_driver_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    where = where + " and   orden.ord_driver_date >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee0.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee0.Text.Split('/');
                    //where = where + " and  case when orden.ord_failed_driver is null then orden.ord_driver_date else orden.ord_driver_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    where = where + " and orden.ord_driver_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }


            }
            else if (cb_searchby.SelectedValue.ToUpper().Equals("PROCESSOR")) {
                processor = 1;
                if (!tb_stardatefee.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee.Text.Split('/');
                    //where = where + " and case when orden.ord_failed_processor is null then orden.ord_processor_date else orden.ord_processor_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    where = where + " and orden.ord_processor_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee.Text.Split('/');
                    //where = where + " and case when orden.ord_failed_processor is null then orden.ord_processor_date else orden.ord_processor_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    where = where + "  and orden.ord_processor_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }

            }
            else if (cb_searchby.SelectedValue.ToUpper().Equals("QC"))
            {
                qc = 1;
                if (!tb_stardatefee1.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee1.Text.Split('/');
                    //where = where + " and  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_qc_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    where = where + "  and orden.ord_qc_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee1.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee1.Text.Split('/');
                    //where = where + " and  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_qc_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    where = where + "  and orden.ord_qc_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }
            }
            else if (cb_searchby.SelectedValue.ToUpper().Equals("PHOTOS"))
            {
                photos = 1;
                if (!tb_stardatefee2.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee2.Text.Split('/');
                    where = where + " and   orden.ord_upload_date >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee2.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee2.Text.Split('/');
                    where = where + " and  orden.ord_upload_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }
            
            
            }
            else if (cb_searchby.SelectedValue.ToUpper().Equals("CLIENT"))
            {
                client = 1;

                if (!tb_stardatefee3.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee3.Text.Split('/');
                    where = where + " and   orden.duedate >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee3.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee3.Text.Split('/');
                    where = where + " and  orden.duedate  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }

                if (cb_typeclient.SelectedIndex != 0 && cb_typeclient.SelectedIndex != -1)
                {

                    if (cb_typeclient.SelectedIndex == 1)//paid
                    {
                        where += " and upper(orden.paid)= 'YES' and orden.status_id<>4 ";
                    }
                    if (cb_typeclient.SelectedIndex == 2) //unpaid
                    {
                        where += " and (orden.paid is null or upper(orden.paid)= 'NO' ) and  orden.status_id<>4";
                    }
                    if (cb_typeclient.SelectedIndex == 3) //canceladas
                    {
                        where += " and    orden.status_id=4";
                    }
                }

                if (cb_acclient.SelectedIndex != 0 && cb_acclient.SelectedIndex!=-1){

                    where += " and orden.account= " + cb_acclient.SelectedValue; ;
                
                
                }

                if (cb_company.SelectedIndex != 0 && cb_company.SelectedIndex != -1) {
                    where += " and orden.company =" + cb_company.SelectedValue;
                }
            }
        }
        // si es el implicito por el usuario en session
        type = (string)Session["typeinvoice"];
        if (type != null && !type.Equals("") ){
            if (!type.Equals("photos")&& !type.Equals("client"))
            {
                //where = " case when orden.ord_failed_" + type + " is null then  orden.ord_" + type + "_done else orden.ord_" + type + "_done  end = 'YES'";
                where = "  orden.ord_" + type + "_done  = 'YES'";
            }
            else {
                where = " orden.ord_uploadby is not null ";
            }
            name =(string) Session["nameinvoice"];
            parametro = cb_searchby.SelectedValue.ToString();
            currency = "GTQ";
            style = "General";
            if (type.ToUpper().Equals("DRIVER"))
            {
                currency = "USD";
                driver = 1;
                parametro = "driver";
                if (uiChbFee.Checked) { fee = " CASE WHEN orden.driver_fee is null then 0.00 ELSE orden.driver_fee END"; }
                else { fee = "  CASE WHEN orden.company = 1  THEN orden.fee ELSE orden.psfprice END "; }
                if (cb_driver.SelectedIndex == -1)
                {
                    name = (string)Session["nameinvoice"];
                    where = "  orden.ord_driver  = '" + name + "'";

                }
                else
                if (cb_driver.SelectedIndex != -1 && cb_driver.SelectedIndex != 0)
                {
                    //where = " case when orden.ord_failed_driver is null then orden.ord_driver else orden.ord_driver end = '" + cb_driver.SelectedValue.ToString() + "'";
                    where = "  orden.ord_driver  = '" + cb_driver.SelectedValue.ToString() + "'";
                }
              //  else { where = ""; }
                  
                
                if (!tb_stardatefee0.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee0.Text.Split('/');
                    //where = where + " and  case when orden.ord_failed_driver is null then orden.ord_driver_date else orden.ord_driver_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    where = where + " and   orden.ord_driver_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee0.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee0.Text.Split('/');
                   // where = where + " and  case when orden.ord_failed_driver is null then orden.ord_driver_date else orden.ord_driver_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    where = where + " and  orden.ord_driver_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }


            }
            else if (type.ToUpper().Equals("PROCESSOR"))
            {
                processor = 1;
                parametro = "processor";
               
                if (cb_processor.SelectedIndex == -1) {
                   name = (string) Session["nameinvoice"] ;
                   if (!where.Equals("")) { where = where + " and "; }
                   where = "  orden.ord_processor  = '" + name + "'";
                }else
                if (cb_processor.SelectedIndex != -1 && cb_processor.SelectedIndex != 0)
                {
                    if (!where.Equals("")) { where = where + " and "; }
                    where = "  orden.ord_processor  = '" + cb_processor.SelectedValue.ToString() + "'";
                }
                else {
                    //where = "";
                }
                if (name != null && name!= "")
                {
                    if (!where.Equals("")) { where = where + " and "; }
                    //where = where +" case when orden.ord_failed_processor is null then orden.ord_processor else orden.ord_processor end   = '" + name + "'";
                    where = where + "  orden.ord_processor    = '" + name + "'";
                }
                if (!tb_stardatefee.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee.Text.Split('/');
                    //where = where + " and case when orden.ord_failed_processor is null then orden.ord_processor_date else orden.ord_processor_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    where = where + "   and orden.ord_processor_date >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee.Text.Split('/');
                    //where = where + " and case when orden.ord_failed_processor is null then orden.ord_processor_date else orden.ord_processor_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    where = where + " and orden.ord_processor_date <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }

            }
            else if (type.ToUpper().Equals("QC"))
            {
                qc = 1;
                parametro = "qc";
                if (cb_qc.SelectedIndex == -1)
                {
                    name = (string)Session["nameinvoice"];
                    
                   // where = "  orden.ord_qc  = '" + name + "'";
                }
                else
                if (cb_qc.SelectedIndex != -1 && cb_qc.SelectedIndex != 0)
                {
                   // where = "  case when orden.ord_failed_qc is null then orden.ord_qc else orden.ord_qc end = ' " + cb_qc.SelectedValue.ToString() + "'";
                    name = cb_qc.SelectedValue.ToString();
                }
                else
                {
                    where = "";
                }
                //where = " case when orden.ord_failed_qc is null then orden.ord_qc else orden.ord_qc end = '" + name + "'";
                if (!tb_stardatefee1.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee1.Text.Split('/');
                  //  where = where + " and  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_qc_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    where = where + " and   orden.ord_qc_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee1.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee1.Text.Split('/');
                    //where = where + " and  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_qc_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    where = where + " and  orden.ord_qc_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }
            }
            else if (type.ToUpper().Equals("PHOTOS")) 
            {
                photos = 1;
                parametro = "photos";
                if (cb_photos.SelectedIndex == -1) {
                   name = (string) Session["nameinvoice"] ;
                   if (!where.Equals("")) { where = where + " and "; }
                   where = "   orden.ord_uploadby  = '" + name + "'";
                }else
                if (cb_photos.SelectedIndex != -1 && cb_photos.SelectedIndex != 0)
                {
                    if (!where.Equals("")) { where = where + " and "; }
                    where = "   orden.ord_uploadby  = '" + cb_photos.SelectedValue.ToString() + "'";
                }
                else {
                   // where = "";
                }
              
                if (!tb_stardatefee2.Text.Equals(""))
                {
                    String[] fecha = tb_stardatefee2.Text.Split('/');
                    where = where + " and   orden.ord_upload_date >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                if (!tb_enddatefee2.Text.Equals(""))
                {
                    String[] fecha2 = tb_enddatefee2.Text.Split('/');
                    where = where + " and   orden.ord_upload_date <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }

            }
            else if (type.ToUpper().Equals("CLIENT"))
            {
                client = 1;
                parametro = "client";
                if (cb_client.SelectedIndex == -1)
                {
                    name = (string)Session["nameinvoice"];
                    if (!where.Equals("")) { where = where + " and "; }
                    where = "   ( orden.client_id  ='"+name+"' ) ";
                }
                else
                    if (cb_client.SelectedIndex != -1 && cb_client.SelectedIndex != 0)
                    {
                        if (!where.Equals("")) { where = where + " and "; }
                        where = "   orden.client_id  = '" + cb_client.SelectedValue.ToString() + "'";
                    }

                /*com.bpophotos.www.Service service = new com.bpophotos.www.Service();
                string xml= service.getTodosDatosUsuario(cb_client.SelectedValue.ToString();
                rUser usercient= Utility.getRUser(xml);
                if (usercient.compname.ToString().Equals("1"))
                {*/
                      if (!tb_stardatefee3.Text.Equals(""))
                    {
                        String[] fecha = tb_stardatefee3.Text.Split('/');
                        where = where + " and   orden.duedate >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    }
                if (!tb_enddatefee3.Text.Equals(""))
                    {
                        String[] fecha2 = tb_enddatefee3.Text.Split('/');
                        where = where + " and   orden.duedate <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    }
                //}
              
                if (cb_typeclient.SelectedIndex != 0 && cb_typeclient.SelectedIndex != -1)
                {

                    if (cb_typeclient.SelectedIndex == 1)
                    {
                        where += " and upper(orden.paid)= 'YES'  and (orden.status_id <> 4 ) ";
                    }
                    if (cb_typeclient.SelectedIndex == 2)
                    {
                        where += " and (orden.paid is null or upper(orden.paid)= 'NO' ) and (orden.status_id <> 4 ) ";
                    }
                    if (cb_typeclient.SelectedIndex == 3)
                    {
                        where += " and (orden.status_id = 4 ) ";
                    }
                    if (cb_acclient.SelectedIndex !=0 && cb_acclient.SelectedIndex != -1){
                        where += " and (orden.account = "+cb_acclient.SelectedValue+" ) ";
                    
                    }
                    if (cb_company.SelectedIndex != 0 && cb_company.SelectedIndex != -1)
                    {
                        where += " and orden.company =" + cb_company.SelectedValue;
                    }
                }

            }
        
        }

        if (cb_processor.SelectedIndex != 0 && cb_processor.SelectedIndex != -1)
        {

            parametro = "processor";
            where = " case when orden.ord_failed_processor is null then orden.ord_processor else orden.ord_processor end   = '" + cb_processor.SelectedValue.ToString()+ "'";
            currency = "GTQ";
            style = "Individual";
            if (!tb_stardatefee.Text.Equals(""))
            {
                String[] fecha = tb_stardatefee.Text.Split('/');
               // where = where + " and case when orden.ord_failed_processor is null then orden.ord_processor_date else orden.ord_processor_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                where = where + " and orden.ord_processor_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddatefee.Text.Equals(""))
            {
                String[] fecha2 = tb_enddatefee.Text.Split('/');
                //where = where + " and case when orden.ord_failed_processor is null then orden.ord_processor_date else orden.ord_processor_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                where = where + " and  orden.ord_processor_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            processor = 1;
        }
        if (cb_driver.SelectedIndex != 0 && cb_driver.SelectedIndex!= -1)
        {
            parametro = "driver";
            where = " case when orden.ord_failed_driver is null then orden.ord_driver else orden.ord_driver end = '" + cb_driver.SelectedValue.ToString() + "'";
            currency = "USD";
            style = "Individual";
            if (!tb_stardatefee0.Text.Equals(""))
            {
                String[] fecha = tb_stardatefee0.Text.Split('/');
                //where = where + " and  case when orden.ord_failed_driver is null then orden.ord_driver_date else orden.ord_driver_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                where = where + " and   orden.ord_driver_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddatefee0.Text.Equals(""))
            {
                String[] fecha2 = tb_enddatefee0.Text.Split('/');
                //where = where + " and  case when orden.ord_failed_driver is null then orden.ord_driver_date else orden.ord_driver_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                where = where + " and  orden.ord_driver_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }

            
            driver = 1;
            if (uiChbFee.Checked) { fee = " CASE WHEN orden.driver_fee is null then 0.00 ELSE orden.driver_fee END"; }
            else { fee = "  CASE WHEN orden.company = 1  THEN orden.fee ELSE orden.psfprice END "; }

        }

        if (cb_qc.SelectedIndex != 0 && cb_qc.SelectedIndex != -1)
        {
            parametro = "qc";
           // where = "  orden.ord_qc  = '" + cb_qc.SelectedValue.ToString() + "'";
            Session["nameinvoice"] = cb_qc.SelectedValue.ToString();
            currency = "GTQ";
            style = "Individual";
            if (!tb_stardatefee1.Text.Equals(""))
            {
                String[] fecha = tb_stardatefee1.Text.Split('/');
                if (!where.Equals(""))
                {
                   // where = where + " and  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_qc_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    where = where + " and  orden.ord_qc_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
                else {
                    //where = where + "  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_qc_date end >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                    where = where + "  orden.ord_qc_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
                }
            }
            if (!tb_enddatefee1.Text.Equals(""))
            {
                String[] fecha2 = tb_enddatefee1.Text.Split('/');
                if (!where.Equals(""))
                {
                   // where = where + " and  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_qc_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    where = where + " and  orden.ord_qc_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }
                else {
                    //where = where + "  case when orden.ord_failed_qc is null then orden.ord_qc_date else orden.ord_qc_date end <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                    where = where + "  case  orden.ord_qc_date  <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
                }
            }
            qc = 1;
        }

        if (cb_photos.SelectedIndex != 0 && cb_photos.SelectedIndex != -1)
        {
            parametro = "photos";

            string initial = cb_photos.SelectedValue.ToString();
            string  alias= initial;
            string xmlalias = "";
            com.bpophotos.www.Service service = new com.bpophotos.www.Service();
            try
            {
               
                xmlalias = service.getTodosDatosUsuarioAlias(initial);
                if (xmlalias != null)
                {
                    rUser temp = Utility.getRUser(xmlalias);
                    if (temp != null)
                    {
                        alias = temp.getUsuarioId();
                    }

                }
            }
            catch (Exception ex)
            {
                Utility.writeError("Error al soliciar al webservice datos de un usuario por inicial");
            }
            finally { 
               if (service!= null) service.Dispose();
            
            }

            where = "  orden.ord_uploadby  = '" + alias + "'";
            currency = "GTQ";
            style = "Individual";
            if (!tb_stardatefee2.Text.Equals(""))
            {
                String[] fecha = tb_stardatefee2.Text.Split('/');
                where = where + " and   orden.ord_upload_date  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddatefee2.Text.Equals(""))
            {
                String[] fecha2 = tb_enddatefee2.Text.Split('/');
                where = where + " and  orden.ord_upload_date <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            photos = 1;
        }
        if (cb_client.SelectedIndex != 0 && cb_client.SelectedIndex != -1)
        {
            parametro = "client";

            string initial = cb_client.SelectedValue.ToString();
            string alias = initial;
            
           
            where = "  orden.client_id  = '" + alias + "'";
            currency = "GTQ";
            style = "Individual";
            if (!tb_stardatefee3.Text.Equals(""))
            {
                String[] fecha = tb_stardatefee3.Text.Split('/');
                where = where + " and   orden.duedate  >='" + fecha[0] + "/" + fecha[1] + "/" + fecha[2] + "'";
            }
            if (!tb_enddatefee3.Text.Equals(""))
            {
                String[] fecha2 = tb_enddatefee3.Text.Split('/');
                where = where + " and  orden.duedate <='" + fecha2[0] + "/" + fecha2[1] + "/" + fecha2[2] + "'";
            }
            client = 1;
            if (cb_typeclient.SelectedIndex != 0 && cb_typeclient.SelectedIndex != -1) {
                //ahora aqui
                if (cb_typeclient.SelectedIndex == 1)//paid
                    {
                        where += " and upper(orden.paid)= 'YES' and orden.status_id<>4 ";
                    }
                    if (cb_typeclient.SelectedIndex == 2) //unpaid
                    {
                        where += " and (orden.paid is null or upper(orden.paid)= 'NO' ) and  orden.status_id<>4";
                    }
                    if (cb_typeclient.SelectedIndex == 3) //canceladas
                    {
                        where += " and    orden.status_id=4";
                    }
            }
            if (cb_acclient.SelectedIndex != 0 && cb_acclient.SelectedIndex != -1){

                where += " and (orden.account = "+cb_acclient.SelectedValue+")";
            
            }
            if (cb_company.SelectedIndex != 0 && cb_company.SelectedIndex != -1)
            {
                where += " and orden.company =" + cb_company.SelectedValue;
            }

        }
        try
        {

            if (driver == 1)
            {

                REPORTDS ds = new REPORTDS();
                string period = tb_stardatefee0.Text + " - " + tb_enddatefee0.Text;
                // Byte[] imagen= CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                where = where + " and orden.ord_driver is not null ";
                ds = DB.getInvoice(where, period, tb_fee.Text, currency, parametro, style, imagen, fee);
                if (ds != null)
                {
                    try
                    {
                        //DriverSumaryReport
                        CrystalDecisions.CrystalReports.Engine.ReportDocument rptsumary = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        rptsumary.Load(Server.MapPath("~/Reports/DriverSummaryInvoice.rpt"));
                        rptsumary.SetDataSource(ds.Tables["order"]);
                        CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        // rpt.SetDatabaseLogon("pacific", "P@cp@cc1f1c", "./sqlexpress", "BPOPhotos");
                        rpt.Load(Server.MapPath("~/Reports/DriverInvoice.rpt"));
                        rpt.SetDataSource(ds);

                        AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabDriver"));
                        if (tabpanel != null)
                        {
                            CrystalDecisions.Web.CrystalReportViewer CRDriver1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRDriver"));
                            if (CRDriver1 != null)
                            {
                                CRDriver1.DisplayGroupTree = false;
                                CRDriver1.ReportSource = rpt;
                                CRDriver1.DataBind();
                                string aux = TabContainer1.ActiveTab.ID;
                            }
                        }

                        Session["rptDriver"] = rpt;
                    }
                    catch (Exception ex)
                    {
                        Utility.writeError("Fail on Crystal Report " + ex.Message + ex.StackTrace);
                    }
                }
                else {
                    Response.Write("<script> alert('Error in Report. Please try again! ');</script>");
                    Utility.writeError("Fail on Crystal Report if" );
                }

            }
            else if (processor == 1)
            {
                REPORTDS ds = new REPORTDS();
                string period = tb_stardatefee.Text + " - " + tb_enddatefee.Text;
                // Byte[] imagen = CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                ds = DB.getInvoice(where, period, tb_fee.Text, currency, parametro, style, imagen,"");
                if (ds != null)
                {
                    try
                    {
                        //ProcessorSumaryReport
                        CrystalDecisions.CrystalReports.Engine.ReportDocument rptsumary = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        rptsumary.Load(Server.MapPath("~/Reports/ProcessorSumaryReport.rpt"));
                        rptsumary.SetDataSource(ds.Tables["order"]);
                        CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        //rpt.SetDatabaseLogon("pacific", "P@cp@cc1f1c", "./sqlexpress", "BPOPhotos");
                        rpt.Load(Server.MapPath("~/Reports/ProcessorInvoice.rpt"));
                        rpt.SetDataSource(ds);

                        AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabProcessor"));
                        if (tabpanel != null)
                        {
                            CrystalDecisions.Web.CrystalReportViewer CRProcessor1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRProcessor"));
                            if (CRProcessor1 != null)
                            {
                                CRProcessor1.DisplayGroupTree = false;
                                CRProcessor1.ReportSource = rpt;
                                CRProcessor1.DataBind();
                                //CrystalProc.Width = new Unit("100%");
                                //CrystalProc.ToolPanelWidth = new Unit("100%");
                                //CrystalProc.BestFitPage = true;
                                string aux = TabContainer1.ActiveTab.ID;
                            }
                        }

                        Session["rptProcessor"] = rpt;

                        
                    }
                    catch (Exception ex) {
                        Utility.writeError("Fail on Crystal Report "+ex.Message + ex.StackTrace);
                    }
                }
                else
                {
                    Response.Write("<script> alert('Error in Report. Please try again!  ');</script>");
                    Utility.writeError("Fail on Crystal Report if" );
                }

            }
            else if (qc==1){
                REPORTDS ds = new REPORTDS();
                string period = tb_stardatefee1.Text + " - " + tb_enddatefee1.Text;
                // Byte[] imagen = CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                name = (string)Session["nameinvoice"];
              
                Session["nameinvoice"] = "";
                ds = DB.getInvoiceQC(where, period, tb_fee.Text, currency, parametro, style, imagen, name, tb_stardatefee1.Text, tb_enddatefee1.Text );
                if (ds != null)
                {
                    try
                    {
                        CrystalDecisions.CrystalReports.Engine.ReportDocument rptsumary = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        rptsumary.Load(Server.MapPath("~/Reports/ProcessorSumaryReport.rpt"));
                        rptsumary.SetDataSource(ds.Tables["order"]);
                        CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();

                        rpt.Load(Server.MapPath("~/Reports/QcInvoice.rpt"));
                        rpt.SetDataSource(ds);
                        //ProcessorSumaryReport

                        AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabQC"));
                        if (tabpanel != null)
                        {
                            CrystalDecisions.Web.CrystalReportViewer CRQC1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRQC"));
                            if (CRQC1 != null)
                            {
                                CRQC1.DisplayGroupTree = false;
                                CRQC1.ReportSource = rpt;
                                CRQC1.DataBind();
                                string aux = TabContainer1.ActiveTab.ID;
                            }
                        }

                        Session["rptQC"] = rpt;
                    }
                    catch (Exception ex)
                    {
                        Utility.writeError("Fail on Crystal Report " + ex.Message + ex.StackTrace);
                    }
                }
                else
                {
                    Response.Write("<script> alert('Error in Report. Please try again!  ');</script>");
                    Utility.writeError("Fail on Crystal Report if" );
                }
                
            }else if (photos==1){
                REPORTDS ds = new REPORTDS();
                string period = tb_stardatefee2.Text + " - " + tb_enddatefee2.Text;
                // Byte[] imagen = CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                ds = DB.getInvoice(where, period, tb_fee.Text, currency, parametro, style, imagen,"");
                 if (ds != null)
                {
                    try
                    {
                        //ProcessorSumaryReport
                        CrystalDecisions.CrystalReports.Engine.ReportDocument rptsumary = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        rptsumary.Load(Server.MapPath("~/Reports/ProcessorSumaryReport.rpt"));
                        rptsumary.SetDataSource(ds.Tables["order"]);
                        CrystalDecisions.CrystalReports.Engine.ReportDocument rpt = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
                        //rpt.SetDatabaseLogon("pacific", "P@cp@cc1f1c", "./sqlexpress", "BPOPhotos");

                        rpt.Load(Server.MapPath("~/Reports/ProcessorInvoice.rpt"));
                        rpt.SetDataSource(ds);

                        AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabPhotos"));
                        if (tabpanel != null)
                        {
                            CrystalDecisions.Web.CrystalReportViewer CRPhotos1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRPhotos"));
                            if (CRPhotos1 != null)
                            {
                                CRPhotos1.DisplayGroupTree = false;
                                CRPhotos1.ReportSource = rpt;
                                CRPhotos1.DataBind();
                                string aux = TabContainer1.ActiveTab.ID;
                            }
                        }

                        Session["rptPhotos"] = rpt;
                    }
                    catch (Exception ex)
                    {
                        Utility.writeError("Fail on Crystal Report ");
                    }
                }
                 else
                 {
                     Response.Write("<script> alert('Error in Report. Please try again!  ');</script>");
                     Utility.writeError("Fail on Crystal Report if" );
                 }

            }
            else if (client == 1) {

                REPORTDS ds = new REPORTDS();
                string period = tb_stardatefee3.Text + " - " + tb_enddatefee3.Text;
                // Byte[] imagen = CargarImagen(Server.MapPath("~/Reports/images/logo.bmp"));//Cargo La imagen
                Byte[] imagen = CargarImagen("C:\\TEMP\\logo2.jpg");//Cargo La imagen
                ds = DB.getInvoiceClient(where, period, tb_fee.Text, currency, parametro, style, imagen);
                if (ds != null)
                {
                    try
                    {
                        gv_client.DataSource = ds.Tables[0];
                        gv_client.DataBind();
                        PClient.Visible = true;
                        Session["dsclient"] = ds;
                        //chkall.Visible = true;
                        lnk_generate.Visible = true;
                        lnk_searchfee.Visible = true;
                        lberror.Visible = false;
                        if (ds.Tables[0].Rows.Count==0){
                            lberror.Text = "No Orders are found";
                            chkall.Visible = false;
                            lberror.Visible = true;
                            lnk_generate.Visible = false;
                            LinkButton2.Visible = false;
                        }
                        
                       
                    }
                    catch (Exception ex)
                    {
                        Utility.writeError("Fail on Crystal Report ");
                    }
                }
                else
                {
                    Response.Write("<script> alert('Error in Report. Please try again!  ');</script>");
                    Utility.writeError("Fail on Crystal Report if");
                }
            
            }

            cb_searchby.SelectedIndex = 0;
            cb_driver.SelectedIndex = 0;
            cb_processor.SelectedIndex = 0;
            cb_qc.SelectedIndex = 0;
            cb_photos.SelectedIndex = 0;
            //cb_client.SelectedIndex = 0;
            tb_stardatefee.Text = "";
            tb_enddatefee.Text = "";
            tb_stardatefee0.Text = "";
            tb_enddatefee0.Text = "";
            tb_stardatefee1.Text = "";
            tb_enddatefee1.Text = "";
            tb_stardatefee2.Text = "";
            tb_enddatefee2.Text = "";
            tb_stardatefee3.Text = "";
            tb_enddatefee3.Text = "";
        } catch(Exception ex){
            Utility.writeError("Error al generar Invoice "+ ex.Message+ ex.StackTrace);
        }

       

    }

    public static Byte[] CargarImagen(string rutaArchivo)
    {


        if (rutaArchivo != "")
        {

            try
            {

                FileStream Archivo = new FileStream(rutaArchivo, FileMode.Open);//Creo el archivo
                BinaryReader binRead = new BinaryReader(Archivo);//Cargo el Archivo en modo binario

                Byte[] imagenEnBytes = new Byte[(Int64)Archivo.Length]; //Creo un Array de Bytes donde guardare la imagen

                binRead.Read(imagenEnBytes, 0, (int)Archivo.Length);//Cargo la imagen en el array de Bytes
                binRead.Close();

                Archivo.Close();

                return imagenEnBytes;//Devuelvo la imagen convertida en un array de bytes

            }


            catch(Exception ex) 
            {
                Utility.writeError("No leyo imagen"+ex.Message+ex.StackTrace);
                return new Byte[0];
            }

        }

        return new byte[0];

    }



    protected void lnk_searchfee_Click(object sender, EventArgs e)
    {
        if (cb_processor.SelectedIndex != 0 && cb_processor.SelectedIndex != -1)
        {
            String[] name = cb_processor.SelectedItem.ToString().Split('-');
            lb_name.Text = name[1];
           // ModalPopupExtender1.Show();
            mostrarReporte();
        }
        if (cb_driver.SelectedIndex != 0 && cb_driver.SelectedIndex != -1)
        {
            String[] name = cb_driver.SelectedItem.ToString().Split('-');
            lb_name.Text = name[1];
            mostrarReporte();
        }
        if (cb_qc.SelectedIndex != 0  )
        {
            String[] name = cb_qc.SelectedItem.ToString().Split('-');
             lb_name.Text = name[1];
            //ModalPopupExtender1.Show();
            mostrarReporte();
        }
        if (cb_searchby.SelectedIndex != 0)
        {
            lb_name.Text = " All  " + cb_searchby.SelectedValue.ToUpper();
            if (cb_searchby.SelectedIndex == 1)
            {
                mostrarReporte();
            }
            else
            {
                //ModalPopupExtender1.Show();
                mostrarReporte();
            }
        }
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        int mostrarreporte = 0;

        cb_searchby.SelectedValue = cb_searchby4.SelectedValue;
        if (cb_processor.SelectedIndex != 0 && cb_processor.SelectedIndex != -1)
        {
            String[] name = cb_processor.SelectedItem.ToString().Split('-');
            if (name.Length > 1)
                lb_name.Text = name[1];
            else
                lb_name.Text = string.Empty;
            // ModalPopupExtender1.Show();
            
            mostrarReporte();
            mostrarreporte = 1;
        }
                
        if (cb_searchby.SelectedIndex != 0 && cb_searchby.SelectedIndex != -1)
        {
            lb_name.Text = " All  " + cb_searchby.SelectedValue.ToUpper();
            if (cb_searchby.SelectedIndex == 1)
            {
                mostrarReporte();
                mostrarreporte = 1;
            }
            else
            {
                //ModalPopupExtender1.Show();
                mostrarReporte();
                mostrarreporte = 1;
            }
        }
        type = (string)Session["typeinvoice"];
        if (type != null && !type.Equals(""))
        {
            lb_name.Text = " All  " + type.ToUpper();

            if (mostrarreporte == 0) { mostrarReporte(); }

        }
    }


    protected void gv_client_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow || e.Row.RowType == DataControlRowType.Header)
        {
         e.Row.Cells[1].Style.Add("display", "none");//order_id colum
        // e.Row.Cells[3].Style.Add("display", "none");//order_id colum
            e.Row.Cells[12].Style.Add("display", "none");//ord_processor colum
           e.Row.Cells[13].Style.Add("display", "none");//ord_processor colum
           e.Row.Cells[14].Style.Add("display", "none");//ord_processor colum
           e.Row.Cells[15].Style.Add("display", "none");//ord_processor colum
           e.Row.Cells[16].Style.Add("display", "none");//ord_processor colum
           //e.Row.Cells[16].Style.Add("display", "none");//ord_processor colum
           e.Row.HorizontalAlign = HorizontalAlign.Left;
        }

        if (e.Row.RowType == DataControlRowType.Header) {
            e.Row.Cells[2].Text= "Order #" ;//ordernum colum
            e.Row.Cells[3].Text = "Client";//ordernum colum
            e.Row.Cells[4].Text = "Type ";//ordernum colum
             e.Row.Cells[5].Text = "St #";//ordernum colum
             e.Row.Cells[6].Text = "Address ";//ordernum colum
             e.Row.Cells[7].Text = "City ";//ordernum colum
             e.Row.Cells[8].Text = "Zip ";//ordernum colum
             e.Row.Cells[9].Text = "Status ";//ordernum colum
             e.Row.Cells[10].Text = "Date ";//ordernum colum
             e.Row.Cells[11].Text = "Fee ";//ordernum colum

             
        }

         if (e.Row.RowType == DataControlRowType.DataRow) {

             string paid = e.Row.Cells[12].Text;
             if (paid != "YES")
             {
                 e.Row.FindControl("image").Visible = false;
                 
             }
             else {
                 e.Row.FindControl("CHK1").Visible = false;
             }
           
         }
    }
    protected void chkall_CheckedChanged(object sender, EventArgs e)
    {
        CheckBox ch = (CheckBox)sender;
        if (ch != null) {
            if (ch.Checked) {
                Check_chequed(ch, true, gv_client);
            } 
            else {
                Check_chequed(ch, false, gv_client);
            }
        }
    }

   

    private void Check_chequed(CheckBox ch, bool p, GridView gv)
    {
        foreach (GridViewRow ROW in gv.Rows)
        {


            CheckBox chk = (CheckBox)ROW.FindControl("CHK1");
            if (p)
            {
                chk.Checked = true;
            }
            else
            {
                chk.Checked = false;
            }

        }
    }
    protected void LinkButton2_Click(object sender, EventArgs e)
    {
        string usuid = "";
        double amount = 0.00;
        string itemnumber = "";

        string butadd = "<form   action='https://www.paypal.com/cgi-bin/webscr' method='post' target='_blank'>";
        butadd += "<input type='hidden' name='cmd' value='_cart' />";
        //butadd += "<input type='hidden' name='add' value='1' />";
        butadd += "<input type='hidden' name='upload' value='1' />";
        butadd += "<input type='hidden' name='business' value='UC5TPPY3Z8XBN' />";
        
         
         
         butadd += "<input type='hidden' name='lc' value='US' />";
         butadd += "<input type='hidden' name='currency_code'; value='USD' />";

        usuid = (string)Session["nameinvoice"];
        if (cb_client.SelectedIndex != 0 && cb_client.SelectedIndex != -1) { usuid = cb_client.SelectedValue.ToString(); }


        com.bpophotos.www.Service service = new com.bpophotos.www.Service();
        string x = service.getDatosUsuario(usuid);
        rUser ru = Utility.getRUser(x);
        int cont = 1;
        foreach (GridViewRow ROW in gv_client.Rows)
        {

            CheckBox chk = (CheckBox)ROW.FindControl("CHK1");
           
            if (chk.Checked)
            {
                
                Label lbfee = (Label)ROW.FindControl("lbFee");
                Label lbid = (Label)ROW.FindControl("lbOrder");
                Label lbnum = (Label)ROW.FindControl("lbOrdernum");
                //if (!itemnumber.Equals("")) { itemnumber += ";"; }
                //itemnumber+=  lbid.Text.ToString();
                //amount += double.Parse(lbfee.Text);
                //Utility.writeError("Invoice  "+ lbid.Text );


                if (!itemnumber.Equals("")) { itemnumber = ";"; }
                itemnumber = lbid.Text.ToString();
                amount = double.Parse(lbfee.Text);
                if (amount > 0)
                {
                    butadd += "<input type='hidden' name='item_number_" + cont + "' value=' " + itemnumber + " ' />";
                    butadd += "<input type='hidden' name=' item_name_" + cont + "' value='" + usuid + "_" + itemnumber + "' />";
                    //butadd += "<input type='hidden' name='amount_" + cont + "' value='" + amount + "' /> ";
                    butadd += "<input type='hidden' name='amount_" + cont + "'; value='" + amount + "' /> ";
                    //butadd += "<input type=&quot;hidden&quot; name=&quot;quantity_" + cont + "&quot; value=&quot;1.00&quot; />";
                   
                    cont++;
                }
            }
        }
      
           
            //PaypalButt(ru.getNombre()+" "+ru.getApellido(), amount.ToString(), itemnumber);
        butadd += "<input type='image' src='https://www.paypal.com/en_US/i/btn/x-click-but10.gif' name='submit' alt='PayPal' /></form>";

            /*lbuy.Text = "<form method=\"post\" action=\"https://www.sandbox.paypal.com/cgi-bin/webscr\" target=\"paypal\">";
lbuy.Text+= "<input type='hidden' name='cmd' value='_cart'>";
lbuy.Text+= "<input type='hidden' name='upload' value='1'>";
lbuy.Text += "<input type='hidden' name='business' value='UFFECEVK5TH58'>";
lbuy.Text+= "<input type='hidden' name='currency_code' value='USD'>";
lbuy.Text+= "<input type='hidden' name='return' value='http://www.bpophotos.com'>";
 
lbuy.Text+= "<input type='text' name='item_name_1' value='Macbook Pro'>";
lbuy.Text+= "<input type='hidden' name='item_number_1' value='001'>";
lbuy.Text+= "<input type='hidden' name='amount_1' value='10'>";
lbuy.Text+= "<input type='hidden' name='quantity_1' value='1'>";
 
lbuy.Text+= "<input type='hidden' name='item_name_2' value='Asus i7'>";
lbuy.Text+= "<input type='hidden' name='item_number_2' value='002'>";
lbuy.Text+= "<input type='hidden' name='amount_2' value='20'>";
lbuy.Text+= "<input type='hidden' name='quantity_2' value='1'> ";
lbuy.Text+= "<input type='image' src='http://images.paypal.com/en_US/i/btn/x-click-but22.gif' border='0' name='submit' width='87' height='23' alt='Make payments with PayPal - it's fast, free and secure!'>";
lbuy.Text+= "</form>";
             * */
            lbuy.Text = butadd;
            p_hide_ModalPopupExtender.Show();
        
    }
    protected void lnk_cancelpaid_Click(object sender, EventArgs e)
    {
        p_hide_ModalPopupExtender.Hide();
    }
    protected void LinkButton3_Click(object sender, EventArgs e)
    {
        lnk_generate.Visible = false;
        PClient.Visible = false;
        //ProcessorSumaryReport
        DataSet ds= (DataSet)Session["dsclient"];
        
        

        if (ds != null)
        {
           
            ds.Tables[0].PrimaryKey =  new DataColumn[] {ds.Tables[0].Columns[0]};
            //Buscando row en Data Set
            foreach (GridViewRow ROW in gv_client.Rows)
            {

                CheckBox chk = (CheckBox)ROW.FindControl("CHK1");

                if (!chk.Checked)
                {

                    Label lbfee = (Label)ROW.FindControl("lbFee");
                    Label lbid = (Label)ROW.FindControl("lbOrder");
                    Label lbnum = (Label)ROW.FindControl("lbOrdernum");
                    string s = lbid.Text;
                    DataRow foundRow = ds.Tables[0].Rows.Find(s);
                    
                    if (foundRow != null)
                    {
                        ds.Tables[0].Rows.Remove(foundRow);
                        
                    }

                }
            }




            CrystalDecisions.CrystalReports.Engine.ReportDocument rptsumary = new CrystalDecisions.CrystalReports.Engine.ReportDocument();
            rptsumary.Load(Server.MapPath("~/Reports/ClientInvoice.rpt"));
            rptsumary.SetDataSource(ds);

            AjaxControlToolkit.TabPanel tabpanel = ((AjaxControlToolkit.TabPanel)TabContainer1.FindControl("TabClient"));
            if (tabpanel != null)
            {
                CrystalDecisions.Web.CrystalReportViewer CRClient1 = ((CrystalDecisions.Web.CrystalReportViewer)tabpanel.FindControl("CRClient"));
                if (CRClient1 != null)
                {
                    CRClient1.DisplayGroupTree = false;
                    CRClient1.ReportSource = rptsumary;
                    CRClient1.DataBind();
                    string aux = TabContainer1.ActiveTab.ID;
                }
            }

            Session["rptClient"] = rptsumary;
        }
    }
    protected void lnk_searchfee0_Click(object sender, EventArgs e)
    {
        int mostrarreporte = 0;

        cb_searchby.SelectedValue = cb_searchby0.SelectedValue;
        if (cb_driver.SelectedIndex != 0 && cb_driver.SelectedIndex != -1)
        {
            String[] name = cb_driver.SelectedItem.ToString().Split('-');
            if (name.Length > 1)
                lb_name.Text = name[1];
            else
                lb_name.Text = string.Empty;
            mostrarReporte();
            mostrarreporte = 1;
        }

        if (cb_searchby.SelectedIndex != 0 && cb_searchby.SelectedIndex != -1)
        {
            lb_name.Text = " All  " + cb_searchby.SelectedValue.ToUpper();
            if (cb_searchby.SelectedIndex == 1)
            {
                mostrarReporte();
                mostrarreporte = 1;
            }
            else
            {
                //ModalPopupExtender1.Show();
                mostrarReporte();
                mostrarreporte = 1;
            }
        }
        type = (string)Session["typeinvoice"];
        if (type != null && !type.Equals(""))
        {
            lb_name.Text = " All  " + type.ToUpper();

            if (mostrarreporte == 0) { mostrarReporte(); }

        }
    }
    protected void lnk_searchfee1_Click(object sender, EventArgs e)
    {
        int mostrarreporte = 0;

        cb_searchby.SelectedValue = cb_searchby1.SelectedValue;
        if (cb_qc.SelectedIndex != 0 && cb_qc.SelectedIndex != -1)
        {
            String[] name = cb_qc.SelectedItem.ToString().Split('-');
            if (name.Length > 1)
                lb_name.Text = name[1];
            else
                lb_name.Text = string.Empty;
            //ModalPopupExtender1.Show();
            mostrarReporte();
            mostrarreporte = 1;
        }

        if (cb_searchby.SelectedIndex != 0 && cb_searchby.SelectedIndex != -1)
        {
            lb_name.Text = " All  " + cb_searchby.SelectedValue.ToUpper();
            if (cb_searchby.SelectedIndex == 1)
            {
                mostrarReporte();
                mostrarreporte = 1;
            }
            else
            {
                //ModalPopupExtender1.Show();
                mostrarReporte();
                mostrarreporte = 1;
            }
        }
        type = (string)Session["typeinvoice"];
        if (type != null && !type.Equals(""))
        {
            lb_name.Text = " All  " + type.ToUpper();

            if (mostrarreporte == 0) { mostrarReporte(); }

        }
    }
    protected void lnk_searchfee2_Click(object sender, EventArgs e)
    {
        int mostrarreporte = 0;

        cb_searchby.SelectedValue = cb_searchby2.SelectedValue;
        if (cb_searchby.SelectedIndex != 0 && cb_searchby.SelectedIndex != -1)
        {
            lb_name.Text = " All  " + cb_searchby.SelectedValue.ToUpper();
            if (cb_searchby.SelectedIndex == 1)
            {
                mostrarReporte();
                mostrarreporte = 1;
            }
            else
            {
                //ModalPopupExtender1.Show();
                mostrarReporte();
                mostrarreporte = 1;
            }
        }
        type = (string)Session["typeinvoice"];
        if (type != null && !type.Equals(""))
        {
            lb_name.Text = " All  " + type.ToUpper();

            if (mostrarreporte == 0) { mostrarReporte(); }

        }
    }
    protected void lnk_searchfee3_Click(object sender, EventArgs e)
    {
        PClient.Visible = false;
        lnk_generate.Visible = false;
        int mostrarreporte = 0;

        cb_searchby.SelectedValue = cb_searchby3.SelectedValue;
        if (cb_client.SelectedIndex != 0 && cb_client.SelectedIndex != -1)
        {
            String[] name = cb_client.SelectedItem.ToString().Split('-');
            if (name.Length > 1)
                lb_name.Text = name[1];
            else
                lb_name.Text = string.Empty;
            //ModalPopupExtender1.Show();
            mostrarReporte();
            mostrarreporte = 1;
        }

        if (cb_searchby.SelectedIndex != 0 && cb_searchby.SelectedIndex != -1)
        {
            lb_name.Text = " All  " + cb_searchby.SelectedValue.ToUpper();
            if (cb_searchby.SelectedIndex == 1)
            {
                mostrarReporte();
                mostrarreporte = 1;
            }
            else
            {
                //ModalPopupExtender1.Show();
                mostrarReporte();
                mostrarreporte = 1;
            }
        }
        type = (string)Session["typeinvoice"];
        if (type != null && !type.Equals(""))
        {
            lb_name.Text = " All  " + type.ToUpper();

            if (mostrarreporte == 0) { mostrarReporte(); }

        }
    }
   
}